package com.learn.util;

import jodd.util.CharUtil;

/**
 * Various String utilities.
 */
public class StringUtil extends jodd.util.StringUtil {

    /**
     * 16进制字符串转byte
     * 
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (StringUtil.isEmpty(hexString)) {
            return null;
        }

        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();

        byte[] data = new byte[length];
        for (int i = 0; i < length; i++) {
            int position = i * 2;
            data[i] = (byte) (CharUtil.hex2int(hexChars[position]) << 4 | CharUtil.hex2int(hexChars[position + 1]));
        }

        return data;
    }

    /**
     * Converts bytes to format hex string. <br>
     * e.g. 65 2E 67 2E
     */
    public static String toFormatHexString(byte[] data) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < data.length; i++) {
            sb.append(CharUtil.int2hex((data[i] & 0xF0) >> 4));
            sb.append(CharUtil.int2hex(data[i] & 0x0F));
            sb.append(' ');
        }

        return sb.substring(0, sb.length() - 1);
    }

    /**
     * Converts bytes to format hex string.<br>
     * e.g. 65 2E 67 2E
     */
    public static String toFormatHexString(Byte[] data) {
        byte[] tmp = new byte[data.length];
        System.arraycopy(data, 0, tmp, 0, data.length);
        return toFormatHexString(tmp);
    }
}
